package org.example.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "wWSzvR3xBprjM/6Sfi7L8YijaivGlM5Utq9xxUOCq9E=";

    // Generate JWT
    public static String generateToken(Map<String, Object> claims) {
        Date date = new Date();
        long dateTime = date.getTime();
        long newDate = dateTime + 24 * 60 * 60 * 1000;
        HashMap<String, Object> head = new HashMap<>();
        head.put("alg", "HS256");
        head.put("typ", "JWT");
        SecretKey secretKey = Keys.hmacShaKeyFor(KEY.getBytes());
        return Jwts.builder().setHeader(head)
                .setIssuedAt(date)
                .setExpiration(new Date(newDate)).claim("userInfo", claims)
                .signWith(secretKey, SignatureAlgorithm.HS256).compact();

    }

    // Validate and parse JWT
    public static boolean validateToken(String token) {
        try {
            SecretKey secretKey = Keys.hmacShaKeyFor(KEY.getBytes());
            Claims body = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody();
            return true;
        } catch (ExpiredJwtException e) {
            System.out.println("Token validation error: 令牌已过期");
            return false; // 如果令牌过期，返回false
        } catch (JwtException e) {
            System.out.println("Token validation error: 令牌无效");
            return false; // 如果有其他异常，返回false
        }
    }

    // Get Claims from JWT
    public static Claims getClaimsFromToken(String token) throws Exception {
        try {
            SecretKey secretKey = Keys.hmacShaKeyFor(KEY.getBytes());

            // 解析JWT并获取声明（claims）
            return Jwts.parserBuilder()
                    .setSigningKey(secretKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new Exception("令牌已过期", e);
        } catch (JwtException e) {
            throw new Exception("令牌无效", e);
        }
    }
}
